package com.lolo.presentation.service.poc;

import java.io.IOException;
import java.net.HttpCookie;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.WebServiceRef;

import com.lolo.json.restlet.JsonMetaData;
import com.lolo.json.restlet.JsonServletRequestHandler;
import com.thoughtworks.xstream.XStream;

public class JsonPoPartnerDetailsHandler implements JsonServletRequestHandler {

	private String version;
	private String serviceName;
	
	@Override
	public Object executeRequest(String action, HttpServletRequest data) throws IOException {
		if (action.equals("execute")) {
			String partnerNr = data.getParameter("partnerNr");
			PoPartnerDetailRequest request = new PoPartnerDetailRequest();
			request.setValidateRequest(false);
			request.setPartnerinfo(new PoPartnerInfo());
			request.getPartnerinfo().setPartnerNr(Integer.valueOf(partnerNr));
			try {
				URL wsdlLocation = new URL("http://localhost:8888/itcommon/PartnerDetailPsWs?WSDL");
				QName serviceQName = new QName("http://soa.wgrintra.net/ch/architecture/wsdl", "PartnerDetailServiceService");
				Service service = Service.create(wsdlLocation, serviceQName);
				PartnerDetailService port = service.getPort(PartnerDetailService.class);
//				BindingProvider provider = (BindingProvider)port;
//				provider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:8888/itcommon/PartnerDetailPsWs");
				return port.execute(request);
			} catch (PresentationServiceException e) {
				throw new IOException("exception in presentation services", e);
			}
		} else {
			throw new IOException("action "+action+" is not defined");
		}
	}

	@Override
	public void configureJsonMapping(String action, XStream xStream) throws IOException {
		xStream.omitField(PartnerDetailServiceService.class, "fieldToOmitInTheResponse");  
		xStream.alias("partnerDetailRequest", PoPartnerDetailRequest.class);  
		xStream.alias("partnerDetailResponse", PoPartnerDetailResponse.class);  
	}

	@Override
	public void getMetaData(JsonMetaData meta) throws IOException {
		meta.addAction("execute", "partnerNr").setDescription("get details of partner based on partnerNr");
	}

	@Override
	public void setVersion(String version) {
		this.version = version;
	}

	@Override
	public String getVersion() {
		return this.version;
	}

	@Override
	public void setServiceName(String serviceName) {
		this.serviceName = serviceName;
	}

	@Override
	public String getServiceName() {
		return this.serviceName;
	}

}
